import { Button, message, Select } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import classNames from 'classnames';
import { useClickAway, useSetState } from 'ahooks';
import _ from 'lodash';
import './index.less';

const timeArr = (length: number, addNum: number) =>
  Array.from({ length: length }, (_, i) => {
    const num = i + addNum;
    return num > 9 ? `${num}:00` : `0${num}:00`;
  });

const TimeSelect: React.FC<ITimeSelectProps> = (props) => {
  const [currentTime, setCurrtTime] = useSetState<any>({
    start: '',
    end: '',
  });
  const [startTimes, setStartTimes] = useState<string[]>(timeArr(25, 0));
  const [endTimes, setEndTimes] = useState<string[]>(timeArr(25, 0));
  const [open, setOpen] = useState<boolean>(false);

  const clickTime = (type: 'start' | 'end', time: string) => {
    const obj: any = {};
    obj[type] = time;
    setCurrtTime(obj);
  };

  const setNewTimeArr = (times: string[]) => {
    const newArr = timeArr(25, 0);
    if (times && times.length > 0) {
      for (let i = 0; i < times.length; i++) {
        const start = times[i].split('-')[0];
        const end = times[i].split('-')[1];
        const sIndex = newArr.indexOf(start);
        const eIndex = newArr.indexOf(end);
        if (sIndex > -1 && eIndex > -1) {
          const num = eIndex - sIndex + 1;
          newArr.splice(sIndex, num);
        }
      }
    }
    setStartTimes(newArr);
    setEndTimes(newArr);
  };

  const add = () => {
    if (startTimes.length <= 0 && props.value && props.value.length > 0) {
      setOpen(false);
      return message.warning('已选择全部时点');
    }

    if (!currentTime.start) {
      return message.error('请选择开始时间');
    }
    if (!currentTime.end) {
      return message.error('请选择结束时间');
    }
    const st = currentTime.start.split(':')[0];
    const et = currentTime.end.split(':')[0];

    if (st >= et) {
      return message.error('开始时间必须小于结束时间');
    }

    const str = `${currentTime.start}-${currentTime.end}`;
    const arr = props.value && _.isArray(props.value) ? [...props.value] : [];

    if (arr.length > 0) {
      const startTimes = [];
      for (let i = 0; i < arr.length; i++) {
        const start = arr[i].split('-')[0];
        const startNum = start.split(':')[0];
        if (st < startNum && et >= startNum) {
          return message.error(`当前结束时间不能大于或等于${startNum}:00`);
        }
        startTimes.push(startNum);
      }
      const min = startTimes.sort()[0];
      if (st < min && et > min) {
        return message.error(`当前结束时间不能大于${min}:00`);
      }
    }

    if (arr.indexOf(str) < 0) {
      arr.push(str);
      props.onChange && props.onChange(arr);
      setCurrtTime({
        start: '',
        end: '',
      });
    }
  };

  const onChange = (val: string[], a: any) => {
    props.onChange && props.onChange(val);
  };

  // useEffect(() => {
  //   setNewTimeArr(props.value || []);
  // }, [props.value]);

  return (
    <Select
      dropdownMatchSelectWidth
      placeholder="请选择时点"
      mode="multiple"
      onChange={onChange}
      value={props.value}
      open={open}
      onFocus={() => {
        setOpen(true);
      }}
      dropdownRender={() => (
        <div className="select-dropdown">
          <div className="box">
            <div className="item">
              <div className="title">开始时间</div>
              <div className="list">
                {startTimes.map((v) => {
                  return (
                    <div
                      key={v}
                      className={classNames('list-item', { active: currentTime.start === v })}
                      onClick={() => clickTime('start', v)}
                    >
                      {v}
                    </div>
                  );
                })}
              </div>
            </div>
            <div className="item">
              <div className="title">结束时间</div>
              <div className="list">
                {endTimes.map((v) => {
                  return (
                    <div
                      key={v}
                      className={classNames('list-item', { active: currentTime.end === v })}
                      onClick={() => clickTime('end', v)}
                    >
                      {v}
                    </div>
                  );
                })}
              </div>
            </div>
          </div>
          <div className="footer">
            <Button
              size="small"
              onClick={() => {
                setOpen(false);
              }}
            >
              收起
            </Button>
            <Button size="small" onClick={add} type="primary">
              确定
            </Button>
          </div>
        </div>
      )}
    />
  );
};

interface ITimeSelectProps {
  onChange?: (time?: string[]) => void;
  value?: string[];
}

export default TimeSelect;
